package iSOCK::Controller::Logout;

use DateTime;
use File::Path qw( remove_tree );

use Moose;
use namespace::autoclean;

BEGIN { extends 'iSOCK::Controller::Root' }

=head1 NAME

iSOCK::Controller::Logout - Logout Controller for iSOCK

=head1 DESCRIPTION

[enter your description here]

=head1 METHODS

=cut

sub index :Path :Args(0) {
  my ( $self, $c ) = @_;

  my $app_m = $c->model ( 'App' );

  if ( my $user_r = $app_m->user_r ( $c ) ) {
    for my $session_r ( $app_m->resultset ( 'Session' )->search ({ user_id => $user_r->id }) ) {
      $session_r->delete;
      
      $user_r->update ({ session_id => undef });
      
      $c->log->info ( "[Controller::Logout::index] Nuked " . $session_r->id . " session in DB." );
      
      if ( my $session_path = $c->session->{session_path} ) {
        remove_tree ( $session_path );
        
        if ( -d $session_path ) {
          $c->log->error ( "[Controller::Logout::index] Could not nuke " . $session_r->id . " session in DB." );
        }
        else {
          $c->log->info  ( "[Controller::Logout::index] Nuked $session_path directory." );
        }
      }
    }
  }
  
  $c->delete_session ( "user logged out at " . DateTime->now->iso8601 );

  $c->logout;
  
  $c->stash ( action_succeeded => "Logged out." );
  
  $c->forward ( qw( iSOCK::Controller::Root render_view ) );
}

=head1 AUTHOR

Xavier Caron

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
